package com.example.springboot.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

import com.example.springboot.entity.User;
import com.example.springboot.mapper.RoleMapper;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleMapper roleMapper;

    //用get请求查询数据库信息
    @GetMapping
    public List<User> findAll(){
//        List<User> list = userMapper.findAll();
//        System.out.println(list.get(0).getRole_id());
        return userMapper.findAll();//查询所有数据
    }

    //用post请求对数据库数据进行增加和修改
    @PostMapping
    public Integer save(@RequestBody User user){
        return userService.save(user);//往数据库插入或更新数据
    }


    //删除
    @DeleteMapping("/{id}")
    public Integer delete(@PathVariable Integer id){
        return userMapper.deleteById(id);
    }

    //批量删除
    @PostMapping("/del/batch")
    public Integer deleteBatch(@RequestBody List<Integer> ids){
        Integer num = 0;
        for(int i=0; i<ids.size();i++){
            Integer id = ids.get(i);
            num = userMapper.deleteById(id);
        }
        return num;
    }


    //多条件分页查询
    //接口路径：/users/page?pageNum=1&pageSize=10
    //@RequestParam接收 ?pageNum=1&pageSize=10
    //分页查询的sql语句为 select * from sys_user limit 0,5;  --第一页显示5条
    //                 select * from sys_user limit 5,5;  --第二页显示5条
    // limit第一个参数 = (pageNum - 1) * pageSize，第二个参数=pageSize
    @GetMapping("/page")
    public Map<String,Object> findPage(@RequestParam Integer pageNum,
                                       @RequestParam Integer pageSize,
                                       @RequestParam String username){
        pageNum = (pageNum - 1) * pageSize;
        Integer total = userMapper.selectTotal(username);
        List<User> data = userMapper.selectPage(pageNum,pageSize,username);
        for(User user : data){
            user.setRoleName(roleMapper.findById(user.getRoleId()));
        }
        Map<String,Object> res = new HashMap<>();
        res.put("data",data);
        res.put("total",total);
        return res;
    }

    /**
    *导出接口
    */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception{
        //从数据库中查询出所有数据
        List<User> list = userMapper.findAll();
        //通过工具类创建writer 写出磁盘路径
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("id","ID");
        writer.addHeaderAlias("username","用户姓名");
        writer.addHeaderAlias("userNumber","工号");
        writer.addHeaderAlias("gender","性别");
        writer.addHeaderAlias("phone","电话");
        writer.addHeaderAlias("email","邮箱");
        writer.addHeaderAlias("password","密码");
        writer.addHeaderAlias("roleId","角色");
        writer.addHeaderAlias("createTime","创建时间");

        //一次性写出list中的对象到excel，使用默认样式，强制输出标题
        writer.write(list,true);
        //设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out,true);
        out.close();
        writer.close();
    }

    /**
     * excel导入接口
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public Integer imp(MultipartFile file) throws Exception{
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
//        reader.addHeaderAlias("ID","id");
        reader.addHeaderAlias("用户姓名","username");
        reader.addHeaderAlias("工号","userNumber");
        reader.addHeaderAlias("性别","gender");
        reader.addHeaderAlias("电话","phone");
        reader.addHeaderAlias("邮箱","email");
        reader.addHeaderAlias("密码","password");
        reader.addHeaderAlias("角色","roleId");

        List<User> list = reader.readAll(User.class);
        System.out.println(list);

        return userService.saveBatch(list);
    }
}
